#include "include.h"

_MB_DELAY_T MB_Delay;

static __IO uint32_t fac_us;
static __IO uint32_t fac_ms;

//systick中断服务函数
void SysTick_Handler(void)
{	
  //100us
	MB_Delay.b100us_flag = 1;
	if ( ++MB_Delay.w100us_Cnt >= 10 ) {
		MB_Delay.w100us_Cnt = 0;
		MB_Delay.b1ms_flag = 1;
	}
}
	

void MeBsp_delay_init(void)
{
	/* configure systick */
  systick_clock_source_config(SYSTICK_CLOCK_SOURCE_AHBCLK_NODIV);
  fac_us = system_core_clock / (1000000U);
  fac_ms = fac_us * (1000U);
  
  SysTick->LOAD = 24000;//100us
  
  SysTick->CTRL |= SysTick_CTRL_ENABLE_Msk;
  SysTick->CTRL|=SysTick_CTRL_TICKINT_Msk;//开启SYSTICK中断
  
	USER_Debug_Out("--Delay Hanl Init OK\r\n"); 
}								    

 								   
void MeBsp_delay_us(uint32_t nus)
{		
	u32 ticks;
	u32 told,tnow,tcnt=0;
	u32 reload=SysTick->LOAD;				//LOAD的值	    	 
	ticks=nus*fac_us; 						//需要的节拍数 
	told=SysTick->VAL;        				//刚进入时的计数器值
	while(1)
	{
		tnow=SysTick->VAL;	
		if(tnow!=told)
		{	    
			if(tnow<told)tcnt+=told-tnow;	//这里注意一下SYSTICK是一个递减的计数器就可以了.
			else tcnt+=reload-tnow+told;	    
			told=tnow;
			if(tcnt>=ticks)break;			//时间超过/等于要延迟的时间,则退出.
		}  
	};											    
}  

void MeBsp_delay_ms(uint32_t nms)
{	
	uint16_t num;
	for ( num = 0; num < nms; num++ ) {
		MeBsp_delay_us((u32)(999));
	}
}


void MeBsp_delay_xms(uint32_t nms)
{
	u32 i;
	for(i=0;i<nms;i++) MeBsp_delay_us(1000);
}

			 



































